package client;

import common.Novel;
import common.Request;
import common.Response;
import common.User;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;

public class NovelReaderClient {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket("127.0.0.1", 9090);
        OutputStream os = s.getOutputStream();
        InputStream is = s.getInputStream();
        ObjectOutputStream oos = new ObjectOutputStream(os);
        ObjectInputStream ois = new ObjectInputStream(is);
        Scanner sc = new Scanner(System.in);

        while (true) {
            System.out.println("欢迎使用本小说系统，请按照以下选项操作输入对应的数字：");
            System.out.println("1：登录  2：注册  3：在线阅读小说  4：下载小说  5：上传小说  0：退出");
            System.out.print("请输入:");
            int ch = sc.nextInt();
            if (ch == 1) {
                while (true) {
                    System.out.println("当前操作：用户登录");
                    User user = new User();
                    System.out.print("请输入用户名：");
                    String name = sc.next();
                    System.out.print("请输入密码：");
                    Integer password = sc.nextInt();
                    user.setUname(name);
                    user.setUpassword(password);
                    Request req = new Request("login");
                    req.put("user", user);
                    oos.writeObject(req);
                    oos.reset();
                    Response resp = (Response) ois.readObject();
                    if (resp.isSuccess()) {
                        System.out.println(resp.getMsg());
                        System.out.println("正在返回主菜单");
                        Thread.sleep(1000);
                        break;
                    } else {
                        System.out.println("登录失败," + resp.getMsg());
                        Thread.sleep(1000);
                        break;
                    }

                }
            } else if (ch == 2) {
                while (true) {
                    System.out.println("当前操作：用户注册");
                    User user = new User();
                    System.out.print("请输入用户名：");
                    String name = sc.next();
                    System.out.print("请输入密码：");
                    Integer password = sc.nextInt();
                    user.setUname(name);
                    user.setUpassword(password);
                    Request req = new Request("register");
                    req.put("user", user);
                    oos.writeObject(req);
                    oos.reset();
                    Response resp = (Response) ois.readObject();
                    if (resp.isSuccess()) {
                        System.out.println(resp.getMsg());
                        System.out.println("正在返回主菜单");
                        Thread.sleep(1000);
                        break;
                    } else {
                        System.out.println("注册失败," + resp.getMsg());
                        Thread.sleep(1000);
                        break;
                    }
                }
            } else if (ch == 3) {
                while (true) {
                    System.out.println("当前操作：在线阅读");
                    ArrayList<String> novelType = getNovelTypes(ois, oos);
                    if (novelType == null) {
                        System.out.println("当前无小说提供，返回主菜单中");
                        Thread.sleep(1000);
                        break;
                    } else {
                        Request req = new Request("getNovelList");
                        oos.writeObject(req);
                        oos.reset();
                        Response resp = (Response) ois.readObject();
                        ArrayList<Novel> novels = (ArrayList<Novel>) resp.get("NovelList");
                        System.out.println("请选择以下分类：");
                        int count = 0;
                        for (String s1 : novelType) {
                            System.out.print(++count);
                            System.out.println(":" + s1);
                        }
                        System.out.print("请输入类型对应的数字：");
                        int ch1 = sc.nextInt();
                        String name1 = novelType.get(ch1 - 1);
                        System.out.println(name1 + "类型小说列表：");
                        System.out.println("序号\t名称\t\t\t作者\t\t简介");
                        int count2 = 0;
                        ArrayList<Novel> typeNovels = new ArrayList<>();
                        for (Novel novel : novels) {
                            if (novel.getType() == null) {
                                continue;
                            }
                            if (novel.getType().equals(name1)) {
                                typeNovels.add(novel);
                                System.out.print(++count2);
                                System.out.println(".\t" + novel.getNovelName() + "\t" + novel.getNovelAuthor() + "\t\t" + novel.getIntroduction());
                            }
                        }
                        System.out.print("请输入要阅读的书的序号：");
                        int ch2 = sc.nextInt();
                        Novel novel = typeNovels.get(ch2 - 1);
                        int novelPages = 1;
                        try {
                            while (true) {
                                System.out.println("**************************");
                                Request req1 = new Request("onlineRead");
                                req1.put("novelName", novel.getNovelName());
                                req1.put("novelPages", novelPages);
                                oos.writeObject(req1);
                                oos.reset();
                                Response resp1 = (Response) ois.readObject();
                                if (resp1.isSuccess()) {
                                    char[] buffer = new char[1024];
                                    buffer = (char[]) resp1.get("content");
                                    System.out.println(new String(buffer));
                                    System.out.println("**************************");
                                    System.out.println("1.上一页  2.下一页  3.返回上一级菜单");
                                    System.out.print("请输入操作序号：");
                                    int ch3 = sc.nextInt();
                                    if (ch3 == 1 && novelPages > 1) {
                                        novelPages = novelPages - 1;
                                    } else if (ch3 == 2) {
                                        novelPages = novelPages + 1;
                                    } else if (ch3 == 3) {
                                        System.out.println("返回中");
                                        Thread.sleep(1000);
                                        break;
                                    } else {
                                        System.out.println("输入错误，返回上级菜单中");
                                        Thread.sleep(1000);
                                        break;
                                    }
                                } else {
                                    System.out.println("请求失败，返回上级菜单中");
                                    Thread.sleep(1000);
                                    throw new RuntimeException();
                                }
                            }
                        }catch (RuntimeException e){
                            break;
                        }
                    }
                }
            } else if (ch == 4) {
                while (true) {
                    System.out.println("当前操作：下载小说");
                    ArrayList<String> novelType = getNovelTypes(ois, oos);
                    if (novelType == null) {
                        System.out.println("当前无小说提供，返回主菜单中");
                        Thread.sleep(1000);
                        break;
                    } else {
                        Request req = new Request("getNovelList");
                        oos.writeObject(req);
                        oos.reset();
                        Response resp = (Response) ois.readObject();
                        ArrayList<Novel> novels = (ArrayList<Novel>) resp.get("NovelList");
                        System.out.println("请选择以下分类：");
                        int count = 0;
                        for (String s1 : novelType) {
                            System.out.print(++count);
                            System.out.println(":" + s1);
                        }
                        System.out.print("请输入类型对应的数字：");
                        int ch1 = sc.nextInt();
                        String name1 = novelType.get(ch1 - 1);
                        System.out.println(name1 + "类型小说列表：");
                        System.out.println("序号\t名称\t\t\t作者\t\t简介");
                        int count2 = 0;
                        ArrayList<Novel> typeNovels = new ArrayList<>();
                        for (Novel novel : novels) {
                            if (novel.getType() == null) {
                                continue;
                            }
                            if (novel.getType().equals(name1)) {
                                typeNovels.add(novel);
                                System.out.print(++count2);
                                System.out.println(".\t" + novel.getNovelName() + "\t" + novel.getNovelAuthor() + "\t\t" + novel.getIntroduction());
                            }
                        }
                        System.out.print("请输入要下载的书的序号：");
                        int ch2 = sc.nextInt();
                        Novel novel = typeNovels.get(ch2 - 1);
                        Request req1 = new Request("download");
                        req1.put("novelName", novel.getNovelName());
                        oos.writeObject(req1);
                        oos.reset();
                        Response resp1 = (Response) ois.readObject();
                        if (resp1.isSuccess()) {
                            byte[] contents = (byte[]) resp1.get("content");
                            FileOutputStream fos = new FileOutputStream(new File("E:\\xiaoshuo\\" + novel.getNovelName() + ".txt"));
                            fos.write(contents);
                            System.out.println("下载成功，返回上级菜单中");
                            Thread.sleep(1000);
                            fos.close();
                            break;
                        } else {
                            System.out.println("下载失败" + resp1.getMsg());
                            System.out.println("返回上级菜单中");
                            Thread.sleep(1000);
                            break;
                        }
                    }
                }
            } else if (ch == 5) {
                while (true) {
                    System.out.println("当前操作：上传小说");
                    Novel novel = new Novel();
                    System.out.print("请输入小说名称：");
                    novel.setNovelName(sc.next());
                    System.out.print("请输入小说作者:");
                    novel.setNovelAuthor(sc.next());
                    System.out.print("请输入小说类型:");
                    novel.setType(sc.next());
                    System.out.print("请输入小说简介:");
                    novel.setIntroduction(sc.next());
                    System.out.print("请输入小说完整路径:");
                    String loadstr = sc.next();
                    try {
                        File f = new File(loadstr);
                        FileInputStream fis = new FileInputStream(f);
                        byte[] b = new byte[(int) f.length()];
                        fis.read(b);
                        fis.close();
                        Request req = new Request("upload");
                        req.put("novel", novel);
                        req.put("content", b);
                        oos.writeObject(req);
                        oos.reset();
                        Response resp = (Response) ois.readObject();
                        if (resp.isSuccess()) {
                            System.out.println("上传成功");
                            System.out.println("返回主菜单中");
                            Thread.sleep(1000);
                            break;
                        } else {
                            System.out.println("上传失败，" + resp.getMsg());
                            System.out.println("返回主菜单中");
                            Thread.sleep(1000);
                            break;
                        }
                    } catch (Exception e) {
                        System.out.println("上传失败");
                        e.printStackTrace();
                        System.out.println("返回主菜单中");
                        Thread.sleep(1000);
                        break;
                    }
                }
            } else if (ch == 0) {
                System.out.println("当前操作：退出系统");
                s.close();
                return;
            } else {
                System.out.println("输入指令错误，返回主菜单中");
                Thread.sleep(1000);
            }
        }
    }

    public static ArrayList<String> getNovelTypes(ObjectInputStream ois, ObjectOutputStream oos) {
        try {
            Request req = new Request("getNovelList");
            oos.writeObject(req);
            oos.reset();
            Response resp = (Response) ois.readObject();
            ArrayList<Novel> novels = (ArrayList<Novel>) resp.get("NovelList");
            if (novels == null) {
                return null;
            } else {
                HashSet<String> hashSet = new HashSet<>();
                for (Novel novel : novels) {
                    if (novel.getType() != null) {
                        hashSet.add(novel.getType());
                    }
                }
                ArrayList<String> novelTypes = new ArrayList<>();
                for (String i : hashSet) {
                    novelTypes.add(i);
                }
                return novelTypes;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
}
